package cn.iocoder.yudao.module.erp.service.business.tax.taxrate;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.business.tax.taxrate.vo.TaxRatePageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.business.tax.taxrate.vo.TaxRateSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.business.tax.taxrate.TaxRateDO;
import cn.iocoder.yudao.module.erp.dal.mysql.business.tax.taxrate.TaxRateMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.TAX_RATE_NOT_EXISTS;

/**
 * 税率 Service 实现类
 *
 * @author yy
 */
@Service
@Validated
public class TaxRateServiceImpl implements TaxRateService {

    @Resource
    private TaxRateMapper taxRateMapper;

    @Override
    public Long createTaxRate(TaxRateSaveReqVO createReqVO) {
        // 插入
        TaxRateDO taxRate = BeanUtils.toBean(createReqVO, TaxRateDO.class);
        //判断常用唯一
        List<TaxRateDO> list = taxRateMapper.selectList();
        if(list.size() == 0)
            taxRate.setStatus(true);
        taxRateMapper.insert(taxRate);
        // 返回
        return taxRate.getId();
    }

    @Override
    public void updateTaxRate(TaxRateSaveReqVO updateReqVO) {
        // 校验存在
        validateTaxRateExists(updateReqVO.getId());
        // 更新
        TaxRateDO updateObj = BeanUtils.toBean(updateReqVO, TaxRateDO.class);
        //判断常用唯一
        if(updateObj.getStatus()){
            List<TaxRateDO> list = taxRateMapper.selectList();
            list.forEach( item -> {
                if(item.getStatus()){
                    item.setStatus(false);
                    taxRateMapper.updateById(item);
                }
            });
        }
        taxRateMapper.updateById(updateObj);
    }

    @Override
    public void deleteTaxRate(Long id) {
        // 校验存在
        validateTaxRateExists(id);
        // 删除
        taxRateMapper.deleteById(id);
    }

    private void validateTaxRateExists(Long id) {
        if (taxRateMapper.selectById(id) == null) {
            throw exception(TAX_RATE_NOT_EXISTS);
        }
    }

    @Override
    public TaxRateDO getTaxRate(Long id) {
        return taxRateMapper.selectById(id);
    }

    @Override
    public PageResult<TaxRateDO> getTaxRatePage(TaxRatePageReqVO pageReqVO) {
        return taxRateMapper.selectPage(pageReqVO);
    }

    @Override
    public List<TaxRateDO> getTaxRateSimpleList() {
        return taxRateMapper.selectList();
    }

}